package cn.com.woxitech.dev.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.pili.Hub;
import com.pili.PiliException;
import com.pili.Stream;
import com.pili.Stream.SaveAsResponse;
import com.pili.Stream.SegmentList;
import com.pili.Stream.SnapshotResponse;
import com.qiniu.Credentials;

import cn.com.woxitech.dev.common.Const;

@Service
public class QiniuService {

	
	public String getSnapshotImg(String streamid) {
		// TODO Auto-generated method stub

		Credentials credentials = new Credentials(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY); // Credentials
		// Object
		Hub hub = new Hub(credentials, Const.QINIU_HUB_NAME);
		
		Stream stream = null;
		String status = null;
		
		try {
			
			stream = hub.getStream(streamid);
			status = stream.status().getStatus();
			
		} catch (PiliException e) {
			// TODO Auto-generated catch block
			status = e.getMessage();
		}

		if(status.equals("connected")){

			String fileName = "" + System.currentTimeMillis()/1000;
			
			SnapshotResponse response = null;
			try {
				response = stream.snapshot(fileName, "jpg");
			} catch (PiliException e) {
				// TODO Auto-generated catch block
				return null;
			}
			
			return response.getTargetUrl();
			
		}else {
			
			return null;
		}
		
		
	}
	/*
	 * return 
	 * 回访播放视频地址，为从直播开始到直播结束
	 * */
	public String savePlaybackRecord(String streamid) {
		
		try {
			
			Credentials credentials = new Credentials(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY); // Credentials
			// Object
			Hub hub = new Hub(credentials, Const.QINIU_HUB_NAME);
			Stream stream = null;
			
			stream = hub.getStream(streamid);
			
			SegmentList sl = stream.segments();
			
			long startTime = sl.getStart();// s
			long endTime = sl.getEnd();
			
			String fileName = startTime+"_"+endTime;
			
			SaveAsResponse response = stream.saveAs(fileName, startTime, endTime);
			
			String playback = response.getUrl();
			playback = playback.replace("pili-media.haojs.com.cn", "qiniulive.haojs.com.cn");
			return playback;
			
		}catch(Exception e){
			
			return null;
		}
	}

	/*
	 * 0 - disconnected
	 * 1 - connected
	 * 2 - Not Found
	 * 3 - Segments is null
	 * 4 - 其他
	 * */
	public int getStreamStatus(String streamid) {

		String status = "";
		try {
			Credentials credentials = new Credentials(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY); // Credentials
			// Object
			Hub hub = new Hub(credentials, Const.QINIU_HUB_NAME);

			Stream stream = hub.getStream(streamid);

			SegmentList sl = stream.segments();
			
			status = stream.status().getStatus();

		} catch (PiliException e) {
			// TODO Auto-generated catch block
			status = e.getMessage();
		}
		
		if(status.equals("disconnected")){
			return 0;
		}else if(status.equals("connected")){
			return 1;
		}else if(status.equals("Not Found")){
			return 2;
		}else if(status.equals("Segments is null")){
			return 3;
		}else{
			return 4;
		}
	}

	/*
	 * map:
	 * streamid, publishurl, playurl
	 * */
	public Map<String, Object> createQiniuStream() throws PiliException {
		// TODO Auto-generated method stub
		Map<String, Object> mp = new HashMap<String,Object>();
		
		Credentials credentials = new Credentials(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY); // Credentials

		// Object
		Hub hub = new Hub(credentials, Const.QINIU_HUB_NAME);
		// Create a new Stream
		String title = null; // optional, auto-generated as default
		String publishKey = null; // optional, auto-generated as default
		String publishSecurity = "static"; // optional, can be "dynamic" or
											// "static", "dynamic" as default
		Stream stream = null;
		stream = hub.createStream(title, publishKey, publishSecurity);

		System.out.println(stream.toJsonString());
		// {
		// "id":"z1.haojslive.57cf97f6b1d1ff829c047712",
		// "createdAt":"2016-09-07T04:30:46.825Z",
		// "updatedAt":"2016-09-07T04:30:46.825Z",
		// "title":"57cf97f6b1d1ff829c047712",
		// "hub":"haojslive",
		// "disabledTill":0,
		// "disabled":false,
		// "publishKey":"f22b92fb4a977e71",
		// "publishSecurity":"static",
		// "hosts":{
		// "publish":{
		// "rtmp":"pili-publish.haojs.com.cn"
		// },
		// "live":{
		// "hdl":"pili-live-hdl.haojs.com.cn",
		// "hls":"pili-live-hls.haojs.com.cn",
		// "http":"pili-live-hls.haojs.com.cn",
		// "rtmp":"pili-live-rtmp.haojs.com.cn",
		// "snapshot":"pili-live-snapshot.haojs.com.cn"
		// },
		// "playback":{
		// "hls":"100036m.playback1.z1.pili.qiniucdn.com",
		// "http":"100036m.playback1.z1.pili.qiniucdn.com"
		// },
		// "play":{
		// "http":"pili-live-hls.haojs.com.cn",
		// "rtmp":"pili-live-rtmp.haojs.com.cn"
		// }
		// }
		// }
		
		mp.put("streamid", stream.getStreamId());
		mp.put("publishurl", stream.rtmpPublishUrl());
		mp.put("playurl", stream.hlsLiveUrls().get(Stream.ORIGIN));
		return mp;
	}
	
	public String savePlaybackRecord(String streamid, long start, long end){
		Credentials credentials = new Credentials(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY); // Credentials

		String playbackurl = null;
		// Object
		Hub hub = new Hub(credentials, Const.QINIU_HUB_NAME);
		// Create a new Stream
		String title = null; // optional, auto-generated as default
		String publishKey = null; // optional, auto-generated as default
		String publishSecurity = "static"; // optional, can be "dynamic" or
											// "static", "dynamic" as default
		Stream stream = null;

		try {
			
			
			stream = hub.getStream(streamid);

			System.out.println(stream.toJsonString());
			// {
			// "id":"z1.haojslive.57cf97f6b1d1ff829c047712",
			// "createdAt":"2016-09-07T04:30:46.825Z",
			// "updatedAt":"2016-09-07T04:30:46.825Z",
			// "title":"57cf97f6b1d1ff829c047712",
			// "hub":"haojslive",
			// "disabledTill":0,
			// "disabled":false,
			// "publishKey":"f22b92fb4a977e71",
			// "publishSecurity":"static",
			// "hosts":{
			// "publish":{
			// "rtmp":"pili-publish.haojs.com.cn"
			// },
			// "live":{
			// "hdl":"pili-live-hdl.haojs.com.cn",
			// "hls":"pili-live-hls.haojs.com.cn",
			// "http":"pili-live-hls.haojs.com.cn",
			// "rtmp":"pili-live-rtmp.haojs.com.cn",
			// "snapshot":"pili-live-snapshot.haojs.com.cn"
			// },
			// "playback":{
			// "hls":"100036m.playback1.z1.pili.qiniucdn.com",
			// "http":"100036m.playback1.z1.pili.qiniucdn.com"
			// },
			// "play":{
			// "http":"pili-live-hls.haojs.com.cn",
			// "rtmp":"pili-live-rtmp.haojs.com.cn"
			// }
			// }
			// }
			

			SegmentList sl = stream.segments();

			if(sl == null || sl.getSegmentList() == null || sl.getSegmentList().isEmpty()){
				playbackurl = null;
			}else{
				
				if(start == 0){
					start = sl.getStart(); //s
				}
				if(end == 0){
					end = sl.getEnd();	
				}
				
				if(start >= end){
					start = sl.getStart();
					end = sl.getEnd();
				}
				
				String fileName = start+"_"+end;
				SaveAsResponse response = stream.saveAs(fileName, start, end);
				playbackurl = "http://qiniulive.haojs.com.cn/recordings/"+streamid+"/"+start+"_"+end+".m3u8";				
			}
			
			
		} catch (PiliException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return playbackurl;
	} 
	public Map<String, String> getStreamUrlsByStreamId(String streamid) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		Map<String, String> mp = new HashMap<String,String>();
		
		Credentials credentials = new Credentials(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY); // Credentials

		// Object
		Hub hub = new Hub(credentials, Const.QINIU_HUB_NAME);

		String publishurl = "";
		String playurl = "";
		String rtmpurl = "";
		//http://qiniulive.haojs.com.cn/recordings/z1.haojslive.58f6ce03a3d5ec73b81dd8fb/1492569622_1492569675.m3u8
		String recordurl = "";
		Stream stream;
		String json = "";
		try {

			stream = hub.getStream(streamid);
			
//			http://pili-live-hls.haojs.com.cn/haojslive/test123.m3u8

			publishurl = stream.rtmpPublishUrl();
			rtmpurl = stream.rtmpLiveUrls().get(Stream.ORIGIN);
			playurl = stream.hlsLiveUrls().get(Stream.ORIGIN);
			json = stream.toJsonString();
			
			SegmentList sl = stream.segments();
			
			if(sl == null || sl.getSegmentList() == null || sl.getSegmentList().isEmpty()){
				recordurl = "";
			}else{
				long start = sl.getStart();
				long end = sl.getEnd();
				recordurl = "http://qiniulive.haojs.com.cn/recordings/"+streamid+"/"+start+"_"+end+".m3u8";				
			}
		} catch (PiliException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			//Segments is null
		}

		
		mp.put("recordurl", recordurl );
		mp.put("publishurl", publishurl );
		mp.put("playurl",playurl );
		mp.put("rtmpurl",rtmpurl );
		mp.put("json",json );

		return mp;
	}
	
}
